package br.com.padtec.software.snmp.challenge;

import java.io.FileNotFoundException;
import java.io.IOException;
import com.adventnet.snmp.mibs.MibException;
import com.adventnet.snmp.mibs.MibNode;
import com.adventnet.snmp.mibs.MibOperations;
import com.adventnet.snmp.snmp2.UDPProtocolOptions;

public class Main {

  private static final int PORT = 8001;
  private static final String SERVER_HOST = "127.0.0.1";
  private SnmpServer snmpServer;
  private Viewer viewer;
  private MibOperations mibOps;
  private UDPProtocolOptions hostAddress;

  public Main() throws FileNotFoundException, MibException, IOException {
    snmpServer = new SnmpServer();
    mibOps = loadMibOperations("mib/PadtecCampusPartyMib");
    hostAddress = createProtocolOptions(SERVER_HOST, PORT);
    viewer = new Viewer(mibOps, snmpServer, hostAddress);
  }

  /**
   * @param args
   * @throws IOException
   * @throws MibException
   * @throws FileNotFoundException
   * @throws SnmpServerException
   */
  public static void main(String[] args) throws SnmpServerException, FileNotFoundException, MibException, IOException {
    Main main = new Main();
    try {
      main.viewer.setVisible(true);
      main.viewer.pack();

      main.updateData();
    } finally {
      main.snmpServer.shutdown();
    }
  }

  private void updateData() throws SnmpServerException {
    snmpServer.init();

    SnmpListener listener = new SnmpListener();
    while (true) {

      String tableOid = ".1.3.6.1.4.1.1.1.1.1.1.1";
      MibNode tableNode = mibOps.getMibNode(tableOid);
      SnmpBean bean = listener.getBeanData(mibOps, snmpServer, SnmpUtils.MAX_ATTEMPTS, hostAddress, "public",
        SnmpUtils.PACKET_TIMEOUT_IN_MILLIS, tableNode, "1876", tableOid);

      viewer.updateData(bean);
    }
  }

  private MibOperations loadMibOperations(String fileName) throws FileNotFoundException, MibException, IOException {
    MibOperations mibOperations = new MibOperations();
    mibOperations.setParsingLevel(MibOperations.LENIENT);
    mibOperations.loadMibModule(fileName);
    return mibOperations;
  }

  private UDPProtocolOptions createProtocolOptions(String host, int port) {
    UDPProtocolOptions udpOptions = new UDPProtocolOptions();
    udpOptions.setRemoteHost(host);
    udpOptions.setRemotePort(port);
    return udpOptions;
  }
}